<?php

include "include/ini.php";
if (post("host") && post("login") && isset($_POST["password"]) && post("db_name") && !$has_db_settings) {
    
    $fp = fopen($settings_path, 'a');
    $base_url = post('base_url');
    if (!preg_match('#^http://#', $base_url) && !preg_match('#^//#', $base_url)) {
        $base_url = "//" . $base_url;
    }
    
    $base_url = preg_replace("#//$#", "/", $base_url . "/");
    fwrite($fp, '<?php $host = "' . post("host") . '";
                            $login = "' . post("login") . '";
                            $password = "' . post("password") . '";
                            $db_name = "' . post("db_name") . '";
                            define("BASE_URL", "' . $base_url . '");
                                ');
    fclose($fp);
    include $settings_path;
    mysql_connect($host, $login, $password);
    $sql = array();
    $sql['database'] = "CREATE DATABASE IF NOT EXISTS `" . $db_name . "` DEFAULT COLLATE = 'utf8_general_ci'";
    $sql['users'] = ("CREATE TABLE `users` (
         `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
         `login` VARCHAR(30),
         `password` VARCHAR(32),
         `first_name` VARCHAR(15),
         `last_name` VARCHAR(30),
         `short_name` VARCHAR(20),
         `date_reg` DATETIME,
         `admin` TINYINT(1) NOT NULL
       )");
    $sql['food'] = ("CREATE TABLE `food` (
         `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
         `uid` INT(5),
         `date` DATE,
         `order` VARCHAR(4),
         `month` INT(6)
       )");
    $sql['date'] = ("CREATE TABLE `date` (
         `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
         `date` DATE,
         `menu` TEXT,
         `total` TEXT,
         `month` INT(6),
         `disabled` TINYINT(1)
       )");
    foreach ($sql as $k => $q) {
        mysql_query($q);
        if ($k == "database") {
            mysql_select_db($db_name);
        }
    }
    register(post('admin_login'), post('admin_password'), 1);

    redirect(BASE_URL);
} elseif ($has_db_settings) {
    redirect(BASE_URL);
}
include ROOT_PATH . 'tpl/' . basename(__FILE__);
include ROOT_PATH . 'tpl/footer.php';